import requests
from django.http import HttpResponse
import re
from os import path
from django.shortcuts import redirect
from GetFrontEnd import upyunAPI


def GetFrontEnd(requests):
    # postdata = str(requests.body, encoding='utf-8')
    # print(postdata)
    if requests.method == 'GET':
        if "param" in requests.GET:
            realpicurl = upyunAPI.GetMusicPNG(requests.GET["id"])
            return redirect(realpicurl)
    else:
        funname = re.findall("/api\?callback=(.*)", requests.get_full_path())

        # 获取歌词
        if requests.POST["types"] == "lyric":
            data = funname[0] + '''({"lyric":"%s","tlyric":""})''' % MakeLrc(requests.POST["id"])

        # 获取音乐链接
        elif requests.POST["types"] == "url":
            data = funname[0] + '({"url":"%s"})' % upyunAPI.MusicUrls[requests.POST["id"]]
        else:
            data = {"msg": "类型错误"}

        # 获取并返回列表信息
        if requests.POST["id"][0] == "3":
            datadict = MakeList(upyunAPI.MusicDict, requests.POST["id"])
            data = funname[0] + "(" + str(datadict) + ")"
        return HttpResponse(data, content_type="application/json")


def MakeList(MusicDict, Listid):
    allmusicinfo = ""
    for musicid, musicdata in MusicDict[Listid]["data"].items():
        musicinfo = '''{
                            "name": "%s",
                            "id": %s,
                            "ar": [{
                                "name": "%s"
                            }],
                            "al": {
                                "name": "%s",
                                "picUrl": "%s"
                            }
                        },''' % (musicdata["music_name"], musicid, musicdata["ar_name"],
                                 musicdata["al_name"], musicdata["al_picUrl"])
        allmusicinfo += musicinfo
    datastr = '''{
                "playlist": {
                    "creator": {
                    },
                    "tracks": [%s],
                    "coverImgUrl": "%s",
                    "name": "%s",
                    "id": %s
                }
            }''' % (allmusicinfo, MusicDict[Listid]["ListPicUrl"], MusicDict[Listid]["ListName"], Listid)
    # print(datastr)
    return datastr


def MakeLrc(music_id, retry=3):
    Lrcres = upyunAPI.GetMusicLrc(upyunAPI.MusicLrcUrls[music_id][0], upyunAPI.MusicLrcUrls[music_id][1])
    retry -= 1
    if retry >= 0:
        print("第" + str(3 - retry) + "次尝试")
        if path.exists("GetFrontEnd/lrc/" + Lrcres[0]):
            with open("GetFrontEnd/lrc/" + Lrcres[0], "r", encoding="utf-8") as lrcfile:
                Lrc = lrcfile.read()
                Lrc = Lrc.replace("\n", "\\n").replace("\"", "\\\"")
            return Lrc
        else:
            if Lrcres[1]:
                LrcResponse = requests.get(Lrcres[1])
                with open("GetFrontEnd/lrc/" + Lrcres[0], "wb") as down:
                    down.write(LrcResponse.content)
                return MakeLrc(music_id, retry)
    return '暂无歌词'


def refreshList(requests):
    upyunAPI.GetAllMusic()
    return HttpResponse({"msg": "成功"})
